# -*- coding: utf-8 -*-
# @File     : api.py
# @Author   : bingjia
# @Time     : 2020/8/6 18:46
# @Desc     : 设备api视图

from django.apps import apps
from django.utils.translation import ugettext_lazy as _
from django.shortcuts import get_list_or_404, get_object_or_404

from operation.base.api import viewsets
from operation.base.api import response
from operation.base.api import exceptions as exc
from operation.base.utils.parse_data import parse_data
from operation.base.api.utils.decorators import list_route

from . import models
from . import signals
from . import services
from . import validators
from . import permissions


class EquipmentViewSet(viewsets.ModelViewSet):
    """
    设备视图
    """
    permission_classes = (permissions.EquipmentPermission,)

    def _save_uav(self, image, name, company, fly_time, wind_loading):
        """
        保存无人机数据
        """
        is_exist, reason = services.is_uav_already_exist(name)
        if is_exist:
            raise exc.ValidationError(reason)

        uav_model = models.UAV

        uav = uav_model(
            name=name,
            image=image,
            company=company,
            fly_time=fly_time,
            wind_loading=wind_loading,
        )
        try:
            uav.save()
        except Exception as e:
            raise exc.ValidationError(_("uav add failed"))

        signals.uav_registered_signal.send(sender=uav.__class__, project=uav)

        return uav

    def _save_camera(self, image, name, company, visible_pixel, infrared_pixel, project_id):
        """
        保存镜头数据
        """
        is_exist, reason = services.is_camera_already_exist(name)
        if is_exist:
            raise exc.ValidationError(reason)

        camera_model = models.Camera

        camera = camera_model(
            name=name,
            image=image,
            company=company,
            visible_pixel=visible_pixel,
            infrared_pixel=infrared_pixel,
        )
        try:
            camera.save()
        except Exception as e:
            raise exc.ValidationError(_("camera add failed"))

        signals.camera_registered_signal.send(sender=camera.__class__, project=camera)

        return camera

    def list(self, request, *args, **kwargs):
        """
        获取项目设备
        """
        resource_id = kwargs.get("resource_id", None)
        project_model = apps.get_model("projects", "Project")
        project_object = get_object_or_404(project_model.objects.all(), pk=resource_id)

        self.check_permissions(request, 'list', project_object)

        temp_dict = {"uav": None, "camera": None}

        uav_object_list = get_list_or_404(models.UAV.objects.all(), project=project_object)
        if uav_object_list:
            uav_serializer = self.get_serializer(uav_object_list, many=True)
            temp_dict["uav"] = uav_serializer.data

        camera_object_list = get_list_or_404(models.Camera.objects.all(), project=project_object)
        if camera_object_list:
            camera_serializer = self.get_serializer(camera_object_list, many=True)
            temp_dict["camera"] = camera_serializer.data

        return response.Ok(temp_dict)

    def create(self, request, *args, **kwargs):
        """
        创建
        """
        resource_id = kwargs.get("resource_id", None)
        project_model = apps.get_model("projects", "Project")
        project_object = get_object_or_404(project_model.objects.all(), pk=resource_id)

        self.check_permissions(request, 'create', project_object)
        "验证数据"
        try:
            if request.data["type"] == "uav":
                data = parse_data(request.data, cls=validators.UavValidator)
                equipment = services.save_uav(**data)
                # 项目关联
                project_object.uav = equipment
            elif request.data["type"] == "camera":
                data = parse_data(request.data, cls=validators.CameraValidator)
                equipment = services.save_camera(**data)
                # 项目关联
                project_object.camera = equipment
        except exc.ParseError as e:
            raise exc.BadRequest(e.detail)

        serializer = self.get_serializer(equipment)
        return response.Created(serializer.data)

    @list_route(methods=["POST"])
    def delete_equipment(self, request, *args, **kwargs):
        """
        删除设备
        """
        resource_id = kwargs.get("resource_id", None)
        project_model = apps.get_model("projects", "Project")
        project_object = get_object_or_404(project_model.objects.all(), pk=resource_id)

        self.check_permissions(request, 'delete_equipment', project_object)

        equipment_type = request.data.get("equipment_type", None)

        if equipment_type == "uav":
            project_object.uav = None
        elif equipment_type == "camera":
            project_object.camera = None

        return response.NoContent()


class EquipmentAdminViewSet(viewsets.ModelViewSet):
    """
    设备管理视图
    """
    permission_classes = (permissions.EquipmentAdminPermission,)

    def list(self, request, *args, **kwargs):
        """
        群查（项目设备情况）
        """

        self.check_permissions(request, 'list', None)

        temp_dict = {"uav": None, "camera": None}

        uav_object_list = get_list_or_404(models.UAV.objects.all())
        if uav_object_list:
            uav_serializer = self.get_serializer(uav_object_list, many=True)
            temp_dict["uav"] = uav_serializer.data

        camera_object_list = get_list_or_404(models.Camera.objects.all())
        if camera_object_list:
            camera_serializer = self.get_serializer(camera_object_list, many=True)
            temp_dict["camera"] = camera_serializer.data

        return response.Ok(temp_dict)

    @list_route(methods=["POST"])
    def delete_equipment(self, request, *args, **kwargs):
        """
        删除设备
        """
        self.check_permissions(request, 'delete_equipment', None)
        equipment_id = request.data.get("equipment_id", None)
        equipment_type = request.data.get("equipment_type", None)

        if equipment_type == "uav":
            obj = get_object_or_404(models.UAV.objects.get(pk=equipment_id))
        elif equipment_type == "camera":
            obj = get_object_or_404(models.Camera.objects.get(pk=equipment_id))

        obj.delete()
        return response.NoContent()

    def create(self, request, *args, **kwargs):
        """
        创建
        """
        self.check_permissions(request, 'create', None)
        "验证数据"
        try:
            if request.data["type"] == "uav":
                data = parse_data(request.data, cls=validators.UavValidator)
                equipment = services.save_uav(**data)
            elif request.data["type"] == "camera":
                data = parse_data(request.data, cls=validators.CameraValidator)
                equipment = services.save_camera(**data)
        except exc.ParseError as e:
            raise exc.BadRequest(e.detail)

        serializer = self.get_serializer(equipment)
        return response.Created(serializer.data)
